/** @jsxImportSource @emotion/react */
import * as React from "react";
import {
  CCell, Cell, Table, TableBody, TableRow, Text, TableHead,
} from "customize-easy-ui-component";
import {DirectLink, Link as RouterLink} from "../../routing/Link";
import {useFoldForList, useFoldGenerate, useSplitSubCapacity,} from "../hook/useMainRepUrlOr";

//#不能使用@  {管道特性表({theme, orc, rep})}
// export const 管道特性表= ({theme, orc, rep} :{theme: any, orc:any, rep:any}
//   ) => {       const pages: any[][]=[];
//   }; 这个模式: 不支持hook React.useMemo( () => {加上就会报错的。
//最后改成了 <PipelineCharacteristics orc={orc} rep={rep}/> 这样的；useMemo才会不报错！

//实际表5列 和才2列的：宽度可自己调节
const CLnPercents=[['12%',"%","55%"], ['9%',"%","37%","37%"],
                 ['7%',"%","25%","25%","25%"], ['6%',"%","20%","20%","20%","20%"]];
//export const CharacteristRow= ({title, dlPage, rep,where,field,span,pref} : {title:string, dlPage: any,rep: any,where?:number,field:string,span?:number,pref?:string}
//pref=null
const CharacteristRow= (title:string,dlPage: any,field:string,rep: any,where?:number, pref?:string|null, span?:number
) => {
  return <TableRow >
    { pref? <><CCell rowSpan={span}>{pref}</CCell><CCell>{title}</CCell></>
        : pref===null? <CCell>{title}</CCell>
            : <CCell colSpan={2}>{title}</CCell>
    }
    { dlPage.map((p: any, c:number) =>
        <DirectLink key={c} href={`/report/${rep?.modeltype}/ver/${rep?.modelversion}/${rep?.id}/Solidify?ppcode=`+p?.code+'#Solidify'}>
          <CCell key={c}>{
            where===1? p?.svp?.[field] :
                where===2? p?.pa?.[field] :
                    p?.[field]}</CCell>
        </DirectLink>
    ) }
  </TableRow>;
};
/**自带分项模式： 这不是内嵌式的有模板代码的公共模板的分项报告模式。
 * 正规jsx组件的用法需改成英文的。
 * 报错：Imported JSX component Moni监控管理系统 must be in PascalCase or SCREAMING_SNAKE_CASE ；<tag></tag>带儿子的组件名字不能用中文的。
 * */
export const PipelineCharacteristPrf= ({ orc, rep, children } : { orc: any,rep: any,children?: React.ReactNode;}
) => {
  //重组成二维 orc?.单元表?.=> 四个一页的组合。pages[ [1{单元},2,3,undefined ] , ]
  const pages= React.useMemo( () => {
    let pages: any[]=[];
    for(let f=0; f<orc?.单元表?.length; f+=4){
        pages.push( orc?.单元表?.slice(f,f+4) );
    }
    return pages;
  }, [orc?.单元表]);

  const lsBlockMax=useSplitSubCapacity(pages.length,4);
  const {sumArea, areaContent, btnBindUses}=useFoldForList(pages, lsBlockMax,false);
  const frCallback = (dlPage: any, arak:number, pid:number) => {
    const pn=arak * lsBlockMax;     //特性表第几张的 基数
    // console.log("特性表大度的 分页组=",dlPage,"pn=",pn,"arak=",arak,"pid=",pid);
    //注意dlPage：对特性表特别的：实际是1-4个的单元拼凑的对象形式集合[][]。
    const xsize=dlPage.length;
    let 检验员s: any[]=[];
    for (const pp of dlPage) {
      if(pp?.sgm){
        const men =检验员s.find((m: any) => m.name === pp?.sgm.name);
        if(!men)  检验员s.push(pp?.sgm);
      }
    }
    //不能约束跟随断开页pageBreakAfter，可能造成空白页<Table fixed={["62%", "%"]} css={{"@media print": {pageBreakAfter: orc?.最后特性? undefined:'always'} }} tight miniw={800}>
    return <React.Fragment key={pid}>
          <DirectLink  href={`/report/${rep?.modeltype}/ver/${rep?.modelversion}/${rep?.id}/Solidify#Solidify`}>
            <Text  variant="h2" css={{textAlign: 'center', marginTop: '1rem',
              "@media print": {
                pageBreakBefore: 'always', marginTop: 'unset',
              },
            }}
            >压力管道数据表</Text>
          </DirectLink>
          <div css={{display: 'flex', justifyContent: 'flex-end',}}>
            <Text>{orc?.检验结论==='合格'? '证书':'报告'}编号：{rep.isp.no}</Text>
          </div>
          <Table fixed={ CLnPercents[xsize-1]  } css={ {borderCollapse: 'collapse' } } tight  miniw={800}>
            <TableHead>
              <TableRow>
                <CCell colSpan={2}>项目 \ 序号</CCell>
                { dlPage.map((p: any, c:number) =>
                    <CCell key={c}><Text  id={`Characteristics${(pn+pid)*4 + c}`}>{ (pn+pid)*4 + c+1 }</Text></CCell>
                ) }
              </TableRow>
            </TableHead>
            <TableBody>
              {CharacteristRow('管道名称',dlPage,'name',rep, )}
              {CharacteristRow('管道编号',dlPage,'code',rep, )}
              {CharacteristRow('管道级别',dlPage,'level',rep, )}
              {CharacteristRow('材质',dlPage,'材料',rep, 1)}
              {CharacteristRow('介质',dlPage,'工介',rep, 2)}
              {CharacteristRow('公称外径 (mm)',dlPage,'dia',rep, 0,'管道规格',4)}
              {CharacteristRow('公称直径 (mm)',dlPage,'直径',rep, 1,null)}
              {CharacteristRow('公称壁厚 (mm)',dlPage,'thik',rep, 0,null)}
              {CharacteristRow('管道长度(m)',dlPage,'leng',rep, 0,null)}
              {CharacteristRow('起点',dlPage,'start',rep, 0,'起止点',2)}
              {CharacteristRow('终点',dlPage,'stop',rep, 0,null)}
              {CharacteristRow('温度（℃）',dlPage,'设温',rep, 1,'设计条件',2)}
              {CharacteristRow('压力（MPa）',dlPage,'设压',rep, 1,null)}
              {CharacteristRow('温度（℃）',dlPage,'工温',rep, 2,'工作条件',2)}
              {CharacteristRow('压力（MPa）',dlPage,'工压',rep, 2,null)}
              {CharacteristRow('敷设方式',dlPage,'lay',rep, )}
              {CharacteristRow('备注（图号）',dlPage,'图号',rep,2 )}
              {CharacteristRow('管道单元注册编码',dlPage,'rno',rep, )}
            </TableBody>
          </Table>
          <Table fixed={["62%", "%"]}  tight miniw={800}>
            <TableBody>
              <DirectLink  href={`/report/${rep?.modeltype}/ver/${rep?.modelversion}/${rep?.id}/LineDiagram#LineDiagram`}>
                <TableRow>
                  {/*这里备注实际是4个管道单元需分别做录入的。 然后这里合并显示*/}
                  <Cell colSpan={2}>
                    说明：&nbsp;
                    { dlPage.map((p: any, c:number) => p?.mm && <React.Fragment key={c}>
                      &nbsp;{p?.mm}。
                    </React.Fragment> )
                    }
                  </Cell>
                </TableRow>
                <TableRow>
                  <CCell>
                    <div css={{
                      height: '100%',
                      display: 'flex',
                      justifyContent: 'space-between',
                      alignContent: 'space-between',alignItems: 'flex-start'}}>
                      <div><Text>检验：</Text>
                        { 检验员s.map((m: any,k:number) => <React.Fragment key={k}>
                          &nbsp;{m.name}
                        </React.Fragment> )
                        }
                      </div>
                      <div css={{textAlign: 'end'}}><Text >日期</Text>2022-12-31</div>
                    </div></CCell>
                  <CCell><div css={{height: '100%',display: 'flex',justifyContent: 'space-between',alignContent: 'space-between',alignItems: 'flex-start'}}>
                    <div><Text >审核：</Text>  </div>
                    <div css={{textAlign: 'end'}}><Text >日期</Text>2021-01-31</div>
                  </div></CCell>
                </TableRow>
              </DirectLink>
            </TableBody>
          </Table>
        {orc?.检验结论==='合格' &&
            <Text css={{fontSize:'0.75rem'}}>注：本表作为《压力管道监督检验证书（压力管道安装、改造和重大修理）》的附表。</Text>
        }
    </React.Fragment>
  };
  const [renderAll]=useFoldGenerate({sumArea,btnBindUses,areaContent, callback:frCallback,mark:'特性表折叠'});
  return <>
    { pages.length<=0 && <RouterLink href={`/report/${rep?.modeltype}/ver/${rep?.modelversion}/${rep?.id}/Solidify#Solidify`}>
            <Text id='Solidify' variant="h2" css={{textAlign: 'center', marginTop: '1rem',
                 "@media print": {display: 'none',},
            }}>管道特性表的单元选择</Text>
          </RouterLink>
    }
    <div id="Characteristics"></div>
    { renderAll }
    { children }
  </>;
};

